<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/8
 * Time: 15:12
 */

class shopify_goods_model extends CI_Model
{

    public $limit_rows = 15;

    public function _where($param = array())
    {
        if ($param['goods_name']) {
            $this->db->where("(g.goods_sn LIKE '%{$param['goods_name']}%' OR sg.goods_name LIKE '%{$param['goods_name']}%')");
        }

        if ($param['goods_ids']) {
            $this->db->where("g.goods_id in ({$param['goods_ids']})");
        }

        if ($param['siteweb_ids']) {
            $this->db->where("sg.web_id in ({$param['siteweb_ids']})");
        }

        if ($param['siteweb'] > 0) {
            $this->db->where("sg.web_id = '{$param['siteweb']}'");
        }
    }

    public function goods_list($param = array(), $is_all = 0)
    {
        $this->db->from('shopify_goods AS sg')
            ->select('sg.*,g.shop_price as g_shop_price,g.goods_sn,g.original_img')
            ->join('goods AS g', 'sg.goods_id = g.goods_id', 'left');

        $this->_where($param);

        if ($is_all != 1) {
            $this->db->limit($this->limit_rows,$this->limit_rows * $param['page']);
        }

        $query = $this->db->get();

        $goods_list = array();
        foreach ($query->result_array() as $row) {
            $row['variants'] = unserialize($row['variants']);

            $goods_list[$row['sg_id']] = $row;
        }

        return $goods_list;
    }

    public function get_goods_list()
	{
		$this->db->from('shopify_goods AS sg')->sele;
	}

    public function count($param = array())
    {
        $this->db->from('shopify_goods AS sg')
            ->join('goods AS g', 'sg.goods_id = g.goods_id', 'left');

        $this->_where($param);

        return $this->db->count_all_results();

    }

    public function goods_info($param = array())
    {
        $query = $this->db->from('shopify_goods')->where($param)->get();

        $shopify_goods = $query->row_array();

        return $shopify_goods;
    }

    public function up_shopify_data($sg_id)
    {
        $shopify_goods = $this->goods_info(array('sg_id' => $sg_id));

        $images_query = $this->db->from('goods_album')->order_by('album_sort ASC')->where(['goods_id'=>$shopify_goods['goods_id'],'is_delete'=>0])->get();

        $shopify_goods['images'] = array();
        foreach ($images_query->result_array() AS $row) {
            if (strpos($row['original_img'],'https://') !== false) {
                $shopify_goods['images'][] = array(
                    'src' => $row['original_img']
                );
            } else {
                $shopify_goods['images'][] = array(
                    'src' => 'http://sumerbikini.com' . $row['original_img']
                );
            }

        }

        $shopify_goods['variants'] = unserialize($shopify_goods['variants']);
        $shopify_goods['options'] = array();
        foreach ($shopify_goods['variants'] as $row) {
            $shopify_goods['options'][0]['name'] = 'Size';
            $shopify_goods['options'][0]['values'][] = $row['option1'];

            $shopify_goods['options'][1]['name'] = 'Color';
            $shopify_goods['options'][1]['values'][] = $row['option2'];
        }

        return $shopify_goods;
    }

    /*
     *孙坚 
     *2019/4/13
     *定时任务请求每次查询5条修改商品表
    */
   public function select_up_shopify()
    {
        $this->load->library('shopify_api');


        //每次查询5条修改
        $where['is_batch'] = 1;
        $query = $this->db->from('shopify_goods')
                ->limit(3)
                ->select('sg_id,web_id')
                ->where($where)->get();
        $shopify_goods = $query->result_array();
        // print_R($shopify_goods);die;
        if(empty($shopify_goods)){
            return false;
        }
        foreach ($shopify_goods as $k => $val) {
            sleep(1);
            //查询分类
            $query = $this->db->from('siteweb')->where(array('web_id'=>$val['web_id']))->get();
            $siteweb = $query->row_array();

            $this->shopify_api->initialize($siteweb);
            //调用接口请示
            $shopify_data = $this->up_shopify_data($val['sg_id']);

            $response = $this->shopify_api->upload_goods($shopify_data);
            $this->shopify_goods_model->update_goods($sg_id, $shopify_goods_data);
            //处理shopify图片ID
            foreach ($shopify_data['images'] as $key => $value) {
                //shopify 图片
                $this->db->where(['album_url'=>substr($value['src'],22)]);
                $this->db->update('goods_sku',['img_shopify_id'=>$response['images'][$key]['id']]);
            }
            //处理shopify sku ID
            foreach($shopify_data['variants'] as $key => $value){
                foreach ($response['variants'] as $k => $v) {
                    if($v['sku'] == $value['sku']){
                        $this->db->where(['sku_num_sn'=>substr($value['sku'],2)]);
                        $this->db->update('goods_sku',['sku_shopify_id'=>$v['id']]);
                    }
                }
            }
            //上传SKU图片
            $img_shopify_id = $this->db->from('goods_sku')->where(['goods_id'=>$shopify_data['goods_id']])->select('img_shopify_id')->group_by('img_shopify_id')->get()->result_array();
            foreach ($img_shopify_id as $key => $value) {
                if(empty($value['img_shopify_id'])){
                    continue;
                }

                $sku_shopify_id = $this->db->from('goods_sku')->where(['img_shopify_id'=>$value['img_shopify_id']])->select('sku_shopify_id')->get()->result_array();
                $variant_ids = [];

                foreach ($sku_shopify_id as $k => $v) {
                    $variant_ids[] = $v['sku_shopify_id'];
                }
                $res = array('image'=>array('id'=>$value['img_shopify_id'],'variant_ids'=>$variant_ids));
                $this->shopify_api->shopify_sku_img($response['id'],$value['img_shopify_id'],$res);
            }

            //成功返回进行修改
            if ($response['id']) {
                $this->db->set('shopify_id', $response['id']);
                $this->db->set('is_batch', 0);
                $this->db->where('sg_id', $val['sg_id']);
                $this->db->update('shopify_goods');
            }
        }
    }



    function imgToBase64($img_file) {

        $img_base64 = '';
        if (file_exists($_SERVER['DOCUMENT_ROOT'].$img_file)) {
            $app_img_file = $_SERVER['DOCUMENT_ROOT'].$img_file;

            //echo '<pre>' . print_r($img_info, true) . '</pre><br>';
            $fp = fopen($app_img_file, "r");

            if ($fp) {
                $filesize = filesize($app_img_file);
                $content = fread($fp, $filesize);
                $img_base64 = chunk_split(base64_encode($content));

            }
            fclose($fp);
        }

        return $img_base64;
    }
    public function insert_goods($data = array(), $id = 0)
    {
        $time = time();
        
        $goods_data = array(
            'goods_name' => $data['goods_name'],
            'shop_price' => $data['shop_price'],
            'market_price' => $data['market_price'],
            'body_html' => $data['body_html'],
            'is_sales' => intval($data['is_sales']),
            'variants' => serialize($data['variants']),
            'tags' => $data['tags']
        );
        if($data['is_batch']){
            $goods_data['is_batch'] = $data['is_batch'];
        }
        $sg_id = $id;
        if ($id) {
            $goods_data['update_time'] = $time;
            $goods_data['cate_name'] = $data['cate_name'];
            
            $this->db->where('sg_id', $id);
            $this->db->update('shopify_goods', $goods_data);
        } else {
            $goods_data['goods_id'] = $data['goods_id'];
            $goods_data['goods_sn'] = $data['goods_sn'];
            $goods_data['web_id'] = $data['web_id'];
            $goods_data['shopify_id'] = $data['shopify_id'] ? $data['shopify_id'] : 0;
            $goods_data['add_time'] = $time;
            $cate_name = $this->db->from('category')->select('cate_name')->where(['cate_id'=>$data['cat_id']])->get()->row_array();
            $goods_data['cate_name'] = $cate_name['cate_name'];
            $goods_data['cat_id'] = $data['cat_id'];
            $this->db->insert('shopify_goods', $goods_data);
            
            $sg_id = $this->db->insert_id();
        }

        return $sg_id;
    }
    
    public function get_shopify_id($shoify_id)
    {
        $query = $this->db->from('shopify_goods')->where('shopify_id', $shoify_id)->get();
        
        $shopify_goods = $query->row_array();
    
        if ($shopify_goods) {
            $shopify_goods['variants'] = unserialize($shopify_goods['variants']);
        }
        
        return $shopify_goods;
    }
    
    public function insert_shopify_goods($data = array())
    {
        $shopify_goods = $this->get_shopify_id($data['id']);
        
        if ($shopify_goods) {
           return false;
        }
        
        $variants = array();
        
        $images = array();
        foreach ($data['images'] as $image) {
            $images[] = array(
                'id' => $image['id'],
                'src' => $image['src'],
                'variant_ids' => $image['variant_ids']
            );
        }
        
        $shopify_data = array(
            'goods_name' => $data['title'],
            'goods_url' => $data['handle'],
            'cate_name' => $data['product_type'],
            'variants' => serialize($data['variants']),
            'images' => serialize($images),
            'shopify_id' => $data['id'],
            'body_html'=> $data['body_html'],
            'goods_id' => $data['goods_id'],
            'web_id' => $data['web_id'],
            'add_time' => time()
        );
        print_r($shopify_data);
        //$this->db->where('sg_id', $shopify_goods['sg_id']);
        $this->db->insert('shopify_goods', $shopify_data);
        
        return true;
    }

    public function pu_shopify_goods($goods_id = 0, $web_id = 0)
    {
        $this->db->from("shopify_goods as sg")
            ->select("sg.*,sw.web_name,sw.ab_name")
            ->join('siteweb as sw', 'sg.web_id = sw.web_id', 'left')
            ->where('sw.type = 1');

        if ($goods_id) {
            $this->db->where("sg.goods_id in ({$goods_id})");
        }

        if ($web_id) {
            $this->db->where("sg.web_id = {$web_id}");
        }

        if (!$goods_id && !$web_id) {
            $this->db->where("is_puyuan = 0");
        }

        $query = $this->db->get();


        $list = $query->result_array();

        if (!$goods_id) {
            $where = array('is_puyuan' => 2);

            if ($web_id) {
                $where['web_id'] = $web_id;
            }

            $this->db->update('shopify_goods', $where, "is_puyuan = 0");
        }


        return $list;
    }

    public function update_goods($sg_id, $data = array())
    {
        if ($data['shopify_id']) {
            $this->db->set('shopify_id', $data['shopify_id']);
        }

        if ($data['is_sales']) {
            $this->db->set('is_sales', $data['is_sales']);
        }
 
        $this->db->set('update_time', $data['update_time']);

        $this->db->where('sg_id', $sg_id);
        $this->db->update('shopify_goods');
    }

    public function get_goods_siteweb_list($goods_id)
    {
        $query = $this->db->from('siteweb as s')
            ->select('s.*,sg.sg_id,sg.shopify_id, sg.is_sales')
            ->join('shopify_goods as sg', 's.web_id = sg.web_id', 'left')
            ->where("sg.goods_id = '{$goods_id}' and s.type = 1")
            ->get();

        $siteweb = $query->result_array();

        return $siteweb;
    }

    public function update_web($sg_id,$val){
        $this->db->set('is_sales',$val);
        $this->db->where_in('sg_id', $sg_id);
        $this->db->update('shopify_goods');
    }
}
